package com.ymt.bpm.engine.handler.process.impl;

import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.engine.handler.process.SequenceFlowEventHandler;
import com.ymt.bpm.model.PSeqflow;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import org.activiti.engine.delegate.event.ActivitiSequenceFlowTakenEvent;
import org.activiti.engine.runtime.Execution;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Created by Johnny on 2016/12/24.
 */
@Component
public class SequenceFlowEventHandlerImpl implements SequenceFlowEventHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Override
    public void onTake(ActivitiSequenceFlowTakenEvent se) {
        String tenantId = (String) se.getEngineServices().getRuntimeService().getVariable(se.getExecutionId(), Const.TENANT_ID);
        if (log.isDebugEnabled()) {
            log.debug("onTake tenantId="+tenantId);
            log.debug("onTake seqflow id="+se.getId());
            log.debug("onTake getSourceActivityId="+se.getSourceActivityId());
            log.debug("onTake getSourceActivityName="+se.getSourceActivityName());
            log.debug("onTake getTargetActivityId="+se.getTargetActivityId());
            log.debug("onTake getTargetActivityName="+se.getTargetActivityName());
        }
        if (se.getId()==null || se.getId().length()==0) {
            return; //跳转的线不需要记录
        }
        PSeqflow seqflow = new PSeqflow();
        if (tenantId!=null && tenantId.length()>0 && StringUtils.isNumeric(tenantId)) {
            seqflow.setTenantId(Integer.parseInt(tenantId));
        }
        seqflow.setId(UUID.randomUUID().toString());
        seqflow.setPiEid(se.getProcessInstanceId());
        //seqflow.setPiId(); //set piid later for performance
        seqflow.setSequenceFlow(se.getId());
        seqflow.setSourceActivityId(se.getSourceActivityId());
        seqflow.setTargetActivityId(se.getTargetActivityId());
        seqflow.setTakeTime(DateUtil.getGMTDate());
        dao.insert(Mapper.PSeqflowMapper, "insertSelective", seqflow);
    }

}
